package com.hengmei.smallscreen.ui

import android.Manifest
import android.content.Intent
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.hengmei.smallscreen.base.BaseActivity
import com.hengmei.smallscreen.databinding.ActivityMainBinding
import com.hengmei.smallscreen.event.LiveDataEvent
import com.hengmei.smallscreen.mmkv.DataRepository
import com.hengmei.smallscreen.utils.SerialAction
import com.hengmei.smallscreen.utils.SerialUtils
import com.hengmei.smallscreen.utils.log
import com.hengmei.smallscreen.utils.toast
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch


class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {
    private val requestLocationPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
            if (isPermissionGranted) {

            } else {
                toast("get Permission ERROR")
            }
        }

    override fun initView() {

        requestLocationPermission.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)

        requestLocationPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION)
        requestLocationPermission.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
        requestLocationPermission.launch(Manifest.permission.BLUETOOTH_ADMIN)
        requestLocationPermission.launch(Manifest.permission.BLUETOOTH)
        requestLocationPermission.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        requestLocationPermission.launch(Manifest.permission.READ_PHONE_STATE)

        binding.homeTitle.text = DataRepository.homeTitle

        LiveDataEvent.get().observe(this) {
//            binding.homeTitle.text = it
            if(it.tag==1){
                binding.homeTitle.text = it.value
            }
            if(it.tag==2){

//                recreate(); // 刷新Activity

            }

        }
        binding.ivBattery.setOnClickListener {
            //欣瑞达屏幕隐藏工具栏

            //欣瑞达屏幕隐藏工具栏
            val intent = Intent("show.systemui")
            sendBroadcast(intent)

            /* 跳转蓝牙 ACTION_BLUETOOTH_SETTINGS*/

            val intent2 = Intent("android.settings.BLUETOOTH_SETTINGS")
            startActivity(intent2)


        }

    }
    private var resultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        //处理返回的结果
        val code = result.resultCode //返回码 如：Activity.RESULT_OK、Activity.RESULT_CANCELED
        val data = result.data
        log("resultCode:$code,data:${data?.getStringExtra("tag")}")
    }


    fun initMCU(){

        launch {

            SerialUtils.instance?.initSerialMCU()
            SerialUtils.instance?.channelAction?.consumeAsFlow()?.collect {
                when(it){
                    is SerialAction.ContrastQrCode->{
//                        MyApp.get().toast("收到串口数据${it.code}")
                        var uart = it.bytes
//                        MyApp.get().toast("收到串口数据${bytesToHexString(uart)}")
                        var str = uart.joinToString("") {
                            String.format("%02X", it)
                        }
                        log("uart: $str")
                        var btHead:Byte = 0x01
                        var btHead2:Byte = 0x04
                        var btHeadLength:Byte = 0x07

                        if(uart[0]==btHead&&uart[1]==btHead2&&uart[2]==btHeadLength){
//                            检测到电压
//                          高八位低八位  解析 3、4
                            binding.ivBattery.visibility = View.VISIBLE

                            var dataLength = (uart[3].toInt() and 0x00ff) * 256 + (uart[4].toInt() and 0x00ff)
                            var batLeave = 0 //电池等级
                            //电池正在使用,根据电压显示电量  同时对电池等级锁死,防止出现"跳格"现象

                            if (dataLength in 420..440){
                                batLeave = 5
                            }
                            if (dataLength in 405..420){
                                batLeave = 4
                            }
                            if (dataLength in 383..395){
                                batLeave = 3
                            }

                            if (dataLength in 371..382){
                                batLeave = 2
                            }

                            if (dataLength <= 370){
                                batLeave = 1
                            }
                            when(batLeave){
                                1->{
                                    binding.ivBattery.setImageResource(com.hengmei.smallscreen.R.mipmap.p0)
                                }
                                2->{
                                    binding.ivBattery.setImageResource(com.hengmei.smallscreen.R.mipmap.p1)
                                }
                                3->{
                                    binding.ivBattery.setImageResource(com.hengmei.smallscreen.R.mipmap.p2)
                                }
                                4->{
                                    binding.ivBattery.setImageResource(com.hengmei.smallscreen.R.mipmap.p3)
                                }
                                5->{
                                    binding.ivBattery.setImageResource(com.hengmei.smallscreen.R.mipmap.p4)
                                }
                            }
                        }

                    }
                }
            }



//                var sendByte = byteArrayOf(0x01,0x06,0x05,0x04,0x00)
//                SerialUtils.instance?.sendMCU(sendByte)
//            }
        }
    }

    override fun initViewEvents() {

        setOnClickListener(binding.rvSetting,binding.rvTest,binding.rvHistory,binding.rvFitting)
        initMCU()
        launch {

            repeatForeverWithDelay(10000L){
                var sendByte = byteArrayOf(0x01,0x06,0x05,0x04,0x00)
                SerialUtils.instance?.sendMCU(sendByte)
            }

        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v){
            binding.rvSetting -> {
                resultLauncher.launch(Intent(this, SettingActivity::class.java))
//
//                SettingActivity.start(this)
            }
            binding.rvTest -> {
                DetectionActivity.start(this)
            }
            binding.rvHistory -> {
                HistoryActivity.start(this)
            }
            binding.rvFitting -> {
                DebugActivity.start(this)
            }
        }
    }

// 循环执行 间隔delayMillis 毫秒 action: suspend () -> Unit
    suspend fun repeatForeverWithDelay(delayMillis: Long, action: suspend () -> Unit) {
        while (true) {
            action()
            delay(delayMillis)
        }
    }



}